#!/bin/bash

function unpack_img {
	echo "****** Cleaning dev folders"
	rm -rf ${1} unpack_${1}
	mkdir -p ${1}
	mkdir -p unpack_${1}

	echo "****** Unpacking ${1}.img"
	test_img=`abootimg -i "source_img/${1}.img" 2>&1 | grep "not a valid"`
	cd unpack_${1}
	if [ -n "${test_img}" ] ; then
		echo ">> this is ramdisk only image! Kernel is/should be in seperate kernel.img"
		cp ../source_img/${1}.img ${1}.img
		rkunpack ${1}.img
		mv ${1}.img-raw initrd.img
		rm -f ${1}.img
	else
		echo ">> this image contains ramdisk and kernel"
		abootimg -x ../source_img/${1}.img
	fi	
	cd ..
	echo "****** Extracting ramdisk..."
	cd ${1}
	gzip -dc ../unpack_${1}/initrd.img | cpio -i --make-directories
	cd ..

	echo ""
	echo ""
}

if [ ! -d source_img ] ; then
	echo "You have to run ${0} in the folder containing source_img folder."
	exit 1
fi
if [ ! -n "${1}" ] ; then
	echo "Usage: ${0} [boot] [recovery]"
	exit 0
fi
if [ ! -f "source_img/${1}.img" ] ; then
	echo "source_img/${1}.img doesn't exist!"
	exit 1
fi

unpack_img ${1}
if [ -n "${2}" ] ; then
	unpack_img ${2}
fi
